import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smart_lam/data/model/discovered_device_with_state.dart';
import 'package:smart_lam/routes/app_pages.dart';

class BleDevicesController extends GetxController {
  late AnimationController controller;
  late Animation<Offset> animation;
  late AnimationController scaleController;
  late Animation<double> scaleAnimation;
  // late List<DiscoveredDevice> devices;
  late List<DiscoveredDeviceWithState> devicesWithState;
  // ignore: cancel_subscriptions
  late StreamSubscription<DiscoveredDevice> sub;

  @override
  void onInit() {
    controller = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: NavigatorState(),
    );
    scaleController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: NavigatorState(),
    );
    final curve =
        CurvedAnimation(parent: controller, curve: Curves.easeInOutExpo);
    animation = Tween<Offset>(
            begin: Offset(
                ScreenUtil().setWidth(1100), -ScreenUtil().setWidth(100)),
            end: Offset(0.0, 0.0))
        .animate(curve);
    scaleAnimation = Tween<double>(begin: 0.6, end: 1).animate(curve);
    controller.forward();
    scaleController.forward();
    super.onInit();
    var ble = FlutterReactiveBle();
    devicesWithState = [];
    sub = ble.scanForDevices(withServices: []).listen(
      (device) {
        var index = devicesWithState.indexWhere((e) => e.discoveredDevice.id == device.id);
        if (index == -1) {
          var discoveredDeviceWithState = DiscoveredDeviceWithState(connectionState: DeviceConnectionState.disconnected, discoveredDevice: device);
          devicesWithState.add(discoveredDeviceWithState);
          update();
        }
        print(device);
      },
      onError: (Object e, StackTrace s) {
        print(e);
        print(s);
      },
    );
  }

  // connection
  void connect(DiscoveredDevice d) {
    var ble = FlutterReactiveBle();
    ble.connectToDevice(
      id: d.id,
      // servicesWithCharacteristicsToDiscover: {serviceId: [char1, char2]},
      connectionTimeout: const Duration(seconds: 2),
    ).listen((connectionState) {
      for (var item in devicesWithState) {
        if(item.discoveredDevice.id == d.id) {
          item.connectionState = connectionState.connectionState;
          Get.toNamed<void>(Routes.lamp, arguments: d);
          break;
        }
      }
      update();
    }, onError: (Object error) {
      // Handle a possible error
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    sub.cancel();
  }
}
